package com.ccb.ic.bbs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ccb.ic.query.bbs.PaginationDTO;
import com.ccb.ic.query.bbs.ResultDTO;
import com.ccb.ic.bbs.exception.CustomizeErrorCode;
import com.ccb.ic.bbs.exception.CustomizeException;
import com.ccb.ic.bbs.provider.UserProvider;
import com.ccb.ic.bbs.service.QuestionService;
import com.ccb.ic.bbs.service.UserAccountService;
import com.ccb.ic.bbs.service.UserInfoService;
import com.ccb.ic.bbs.service.UserService;
import com.ccb.ic.domain.bbs.User;
import com.ccb.ic.domain.bbs.UserAccount;
import com.ccb.ic.domain.bbs.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    UserProvider userProvider;


    @GetMapping("bbs/user/{userId}")
    public Object getUserHome(@PathVariable(name = "userId", required = false) String userId,
                              @RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "size", defaultValue = "12") Integer size,
                              HttpServletRequest request) {
        //System.out.println("用户id为："+userId);
        if (userId == null || StringUtils.isBlank(userId)) {
            System.out.println("用户为空!");
            return "redirect:/";
        }
        User user = userService.selectUserByUserId(userId);
        Map<String, Object> model = new HashMap<>();
        if (user != null) {
            UserAccount userAccount = userAccountService.selectUserAccountByUserId(user.getId());
            UserInfo userInfo = userInfoService.selectByUserId(user.getId());
            model.put("user", user);
            model.put("userAccount", userAccount);
            model.put("userInfo", userInfo);
            PaginationDTO paginationDTO = questionService.listByUserId(user.getId(), page, size);
            model.put("paginationDto", paginationDTO);
            return ResultDTO.okOf(model);
        } else {
            model.put("errorCode", CustomizeErrorCode.USER_IS_EMPTY.getCode());
            model.put("message", CustomizeErrorCode.USER_IS_EMPTY.getMessage());
            return ResultDTO.errorOf(model);
        }
        //return "user/home";
    }


    @PostMapping("bbs/user/set/{action}")
    @ResponseBody
    public Map<String, Object> set(HttpServletRequest request,
                                   @PathVariable(name = "action") String action
            , @RequestParam(name = "avatar", defaultValue = "https://niter.cn/images/default-avatar.png") String avatar
            , @RequestParam(name = "json", required = false) String json
            , @RequestParam(name = "data", required = false) String data) {
        User user = userProvider.getUser("token");

        if (user == null) {
            throw new CustomizeException(CustomizeErrorCode.NO_LOGIN);
        }
        Map<String, Object> map = new HashMap<>();

        if ("avatar".equals(action)) {
            //System.out.println(avatar);
            int i = userService.updateAvatarById(user.getId(), avatar);
            if (i == 1) {
                map.put("code", 200);
                map.put("msg", "恭喜您，头像修改成功！！！");
            } else {
                map.put("code", 500);
                map.put("msg", "妈呀，出问题啦！");
            }
        }

        if ("info".equals(action)) {
            System.out.println("json:" + json);
            UserInfo userInfo = JSON.parseObject(json, UserInfo.class);
            JSONObject obj = JSON.parseObject(json);
            userInfo.setLocation(obj.getString("P1") + "-" + obj.getString("C1") + "-" + obj.getString("A1"));
            String[] birthday = userInfo.getBirthday().split("-");
            if (birthday.length == 3) {
                String constellation = userInfoService.getConstellation(Integer.parseInt(birthday[1]), Integer.parseInt(birthday[2]));
                userInfo.setConstellation(constellation);
            }
            int i = userInfoService.updateByUserId(userInfo, user.getId());
            int j = userService.updateUsernameById(user.getId(), obj.getString("username"));

            if (j != 1) {
                map.put("code", 500);
                map.put("msg", "妈呀，昵称修改失败啦！");
            } else if (i != 1) {
                map.put("code", 500);
                map.put("msg", "妈呀，资料修改失败啦！");
            } else {
                map.put("code", 200);
                map.put("msg", "恭喜您，资料修改成功！！！");
            }
        }

        return map;
    }

    @PostMapping("bbs/user/new")
    @ResponseBody
    public Object newUser(@RequestBody Map<String, Object> params) {
        String name = (String) params.get("name");
        String phone = (String) params.get("phone");
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(phone)) {
            return ResultDTO.errorOf("name|phone not is null");
        }
        User user = new User();
        user.setPhone(phone);
        user.setName(name);
        userService.createOrUpdate(user);
        return ResultDTO.okOf("创建成功");
    }


}
